﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
// excel 工具类
namespace TOOLS
{
    public class ExcelUtil<T> where T : new()
    {
        //创建工作簿
        private HSSFWorkbook workbook = null;

        public ExcelUtil()
        {
            this.workbook = new HSSFWorkbook();
        }

        // list : 数据
        // filePath : 导出路径
        public void export(List<T> list, string filePath, string title)
        {


            //创建HSSFSheet表
            HSSFSheet sheet = workbook.CreateSheet(title);
            FillTitle(sheet);
            FillData(list, sheet);
            //输出Excel文件
            FileStream file = new FileStream(filePath, FileMode.Create);
            workbook.Write(file);
            file.Flush();
        }
        // 填入数据
        private void FillData(List<T> dataList, HSSFSheet sheet)
        {
            // 内容从第二行开始(0为开始行)
            int startIndex = 1;
            // 填入数据
            for (int i = 0; i < dataList.Count; i++)
            {
                // 为每一个员工数据创建行
                HSSFRow row = sheet.CreateRow(startIndex + i);
                T temp = dataList[i];
                Type type = temp.GetType();
                // 获取所有属性
                PropertyInfo[] properties = type.GetProperties();
                int index = 0;
                // 遍历成员变量
                for (var f = 0; f < properties.Length; f++)
                {
                    var filed = properties[f];
                    var annotations = filed.GetCustomAttributes(false);
                    for (int j = 0; j < annotations.Length; j++)
                    {
                        // 如果有这个数据注解
                        ExportAttribute t = annotations[j] as ExportAttribute;
                        if (t != null)
                        {
                            //创建列
                            HSSFCell cell = row.CreateCell(index);

                            // 判断是否使用format格式化
                            if (t.Format != null)
                            {
                                Dictionary<string, string> map = getFormatValues(t.Format.Split(','));
                                //设置单元格的值
                                cell.SetCellValue(
                                    map[Convert.ToString(filed.GetValue(temp))]
                                );
                            }
                            else
                            {
                                //设置单元格的值
                                cell.SetCellValue(
                                    Convert.ToString(filed.GetValue(temp))
                                );
                            }

                            index++;
                        }

                    }
                }
            }

        }

        // 填入表头行
        private void FillTitle(HSSFSheet sheet)
        {
            //创建HSSF标题行
            HSSFRow row = sheet.CreateRow(0);
            T temp = new T();
            Type type = temp.GetType();
            // 获取所有属性
            PropertyInfo[] properties = type.GetProperties();
            int index = 0;
            for (var i = 0; i < properties.Length; i++)
            {
                var filed = properties[i];
                var annotations = filed.GetCustomAttributes(false);
                for (int j = 0; j < annotations.Length; j++)
                {
                    // 如果有这个数据注解
                    ExportAttribute t = annotations[j] as ExportAttribute;
                    if (t != null)
                    {
                        //创建列
                        HSSFCell cell = row.CreateCell(index);
                        cell.CellStyle = GetTitLeCellStyle();
                        //设置单元格的值
                        cell.SetCellValue(t.Name);
                        index++;
                    }

                }
            }
        }



        // 取值格式化  如 性别 0=女,1=男  逗号分隔
        private Dictionary<string, string> getFormatValues(string[] vs)
        {
            try
            {
                Dictionary<string, string> map = new Dictionary<string, string>();
                foreach (string s in vs)
                {
                    string[] arr = s.Split('=');
                    map.Add(arr[0], arr[1]);
                }
                return map;
            }
            catch (Exception)
            {
                throw new Exception("format value is wrong");
            }
        }

        // 单元格样式
        private HSSFCellStyle GetTitLeCellStyle()
        {
            HSSFCellStyle cellStyle = workbook.CreateCellStyle();
            cellStyle.VerticalAlignment = HSSFCellStyle.VERTICAL_CENTER;
            //设置前景色
            cellStyle.FillForegroundColor = HSSFColor.GREEN.index;
            //设置背景颜色
            cellStyle.FillBackgroundColor = HSSFColor.GREY_25_PERCENT.index;
            return cellStyle;
        }
    }
}
